<template>
  <div class="info-container box-bg-color main-content">
    <el-form
      ref="infoFormRef"
      :model="infoForm"
      :rules="formRules"
      label-position="right"
      label-width="120px"
      v-loading="loading"
    >
      <el-form-item label="网站名称" prop="webName">
        <el-input v-model="infoForm.webName" placeholder="请输入网站名称"></el-input>
      </el-form-item>
      <el-form-item label="网站描述" prop="description">
        <el-input v-model="infoForm.description" placeholder="请输入网站描述，有利于seo"></el-input>
      </el-form-item>
      <el-form-item label="网站关键词" prop="keywords">
        <el-input v-model="infoForm.keywords" placeholder="请输入网站关键词，有利于seo"></el-input>
      </el-form-item>
      <el-form-item label="品牌名称" prop="brandName">
        <el-input v-model="infoForm.brandName" placeholder="请输入品牌名称"></el-input>
      </el-form-item>
      <el-form-item label="公司名称" prop="companyName">
        <el-input v-model="infoForm.companyName" placeholder="请输入公司名称"></el-input>
      </el-form-item>
      <el-form-item label="公众号名称" prop="wechatPublicName">
        <el-input v-model="infoForm.wechatPublicName" placeholder="请输入公众号名称"></el-input>
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input v-model="infoForm.phone" placeholder="请输入手机号码"></el-input>
      </el-form-item>
      <el-form-item label="公司邮箱" prop="email">
        <el-input v-model="infoForm.email" placeholder="请输入公司邮箱"></el-input>
      </el-form-item>
      <el-form-item label="官方微信号" prop="wechat">
        <el-input v-model="infoForm.wechat" placeholder="请输入官方微信号"></el-input>
      </el-form-item>
      <el-form-item label="Skype" prop="skype">
        <el-input v-model="infoForm.skype" placeholder="请输入Skype"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="infoForm.address" placeholder="请输入地址"></el-input>
      </el-form-item>
      <el-form-item label="版权" prop="copyright">
        <el-input v-model="infoForm.copyright" placeholder="请输入版权"></el-input>
      </el-form-item>
      <el-form-item label="LOGO" prop="logo">
        <el-upload
          accept="image/png, image/jpeg, image/jpg"
          action=""
          :auto-upload="false"
          :show-file-list="false"
          :on-change="uploadClickEvent"
        >
          <el-image :src="logoUrl" class="infoImage">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </el-upload>
      </el-form-item>
      <el-form-item label="二维码" prop="qrCodeUrl">
        <el-upload
          accept="image/png, image/jpeg, image/jpg"
          action=""
          :auto-upload="false"
          :show-file-list="false"
          :on-change="uploadCodeClickEvent"
        >
          <el-image :src="qrCodeUrl" class="infoImage">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </el-upload>
      </el-form-item>
    </el-form>

    <div class="btnBox">
      <el-button type="primary" @click="updateOrCreate">确定</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch, type PropType } from 'vue';
  import { UPDATE_MODEL_EVENT } from 'cm/contants';
  import { validPhone } from '@/utils/validate';
  import { getWebInfo, updateWebInfo, type ICreateOrUpdateInfo } from '@/api/info';
  import { ElMessage } from 'element-plus'
  import { fileUpload, type OssApiResult } from '@/api/oss'
  import appConfig from '@/config/index'

  const defaultForm = {
    webName: '',
    description: '',
    keywords: '',
    brandName: '',
    companyName: '',
    wechatPublicName: '',
    phone: '',
    email: '',
    wechat: '',
    skype: '',
    address: '',
    copyright: '',
    logo: '',
    qrCode: ''
  }
  // 表单逻辑
  const infoForm = ref<ICreateOrUpdateInfo>({ ...defaultForm });

  const validPhoneNum = (rule: any, value: string, callback: any) => {
    if (validPhone(value)) {
      callback()
    } else {
      callback(new Error('请输入正确的手机号'))
    }
  }

  const formRules = {
    webName: [{ required: true, message: '请输入网站名称', trigger: 'blur' }],
    companyName: [{ required: true, message: '请输入网站名称', trigger: 'blur' }],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { validator: validPhoneNum, trigger: 'blur' }
    ],
    email: [{ required: true, message: '请输入公司邮箱', trigger: 'blur' }],
    wechat: [{ required: true, message: '请输入官方微信号', trigger: 'blur' }],
    skype: [{ required: true, message: '请输入Skype', trigger: 'blur' }],
    copyright: [
      { required: true, message: '请输入版权', trigger: 'blur' }
    ]
  }

  const loading = ref<boolean>(false);

  // 查询网站信息详情
  const getWebInfoApi = async () => {
    loading.value = true
    const res = await getWebInfo()
    loading.value = false
    if (res?.code === 200) {
      infoForm.value = res.data as ICreateOrUpdateInfo;
      logoUrl.value = `${appConfig.api.staticUrl}${infoForm.value.logo}`
      qrCodeUrl.value = `${appConfig.api.staticUrl}${infoForm.value.qrCode}`;
    }
  }

  const confirmUpload = async (type: string) => {
    loading.value = true
    const formData = new FormData()
    const cropData = type === 'logo' ? logoUrlRaw.value : qrCodeUrlRaw.value;
    const businessText = type === 'logo' ? '网站Logo' : '网站二维码';

    formData.append('file', cropData)
    formData.append('business', businessText)
    const res = await fileUpload(formData)
    loading.value = false
    if (res?.code === 200) {
      ElMessage({ type: 'success', message: '上传成功' });
      const data = res.data as OssApiResult[];

      if (type === 'logo') {
        infoForm.value.logo = data[0].url;
      }

      if (type === 'qrCode') {
        infoForm.value.qrCode = data[0].url;
      }

    } else {
      ElMessage({ type: 'error', message: res?.msg || '网络异常，请稍后重试' })
    }
  }

  /** logo上传 */
  const logoUrl = ref();
  const logoUrlRaw = ref();
  const uploadClickEvent = async (file: any) => {
    if ('image/png, image/jpeg, image/jpg'.indexOf(file.raw.type) === -1) {
      ElMessage({ type: 'error', message: '文件类型错误' })
      return false
    }
    if (file.raw.size > 1024 * 1024 * 5) {
      ElMessage({ type: 'error', message: '上传图片大小不能超过 5M' })
      return false
    }
    // console.log(file.raw)
    logoUrlRaw.value = file.raw;
    await confirmUpload('logo')
    const reader = new FileReader()
    reader.readAsDataURL(file.raw)
    reader.onload = (e) => {
      logoUrl.value = `${appConfig.api.staticUrl}${infoForm.value.logo}`
    }
  }

  /** 二维码上传 */
  const qrCodeUrl = ref();
  const qrCodeUrlRaw = ref();
  const uploadCodeClickEvent = async (file: any) => {
    if ('image/png, image/jpeg, image/jpg'.indexOf(file.raw.type) === -1) {
      ElMessage({ type: 'error', message: '文件类型错误' })
      return false
    }
    if (file.raw.size > 1024 * 1024 * 5) {
      ElMessage({ type: 'error', message: '上传图片大小不能超过 5M' })
      return false
    }
    qrCodeUrlRaw.value = file.raw
    await confirmUpload('qrCode')
    const reader = new FileReader()
    reader.readAsDataURL(file.raw)
    reader.onload = (e) => {
      qrCodeUrl.value = `${appConfig.api.staticUrl}${infoForm.value.qrCode}`
    }
  }

  const infoFormRef = ref();
  const updateOrCreate = async () => {
    infoFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
        loading.value = true
        const res = await updateWebInfo(infoForm.value)
        loading.value = false
        if (res?.code === 200) {
          ElMessage({ type: 'success', message: '更新成功' })
          getWebInfoApi();
        } else {
          ElMessage({ type: 'error', message: res?.msg || '网络异常，请稍后重试！' })
        }
      }
    })
  }

  getWebInfoApi();
</script>

<style lang="scss" scoped>
  .btnBox {
    width: calc(100% - var(--sidebar-width));
    padding: 20px;
    background-color: #fff;
    position: fixed;
    bottom: 0;
    left: var(--sidebar-width) !important;
    z-index: 3;
    display: flex;
    justify-content: flex-end;
    box-shadow: -6px 0px 16px 0 rgba(0,0,0,0.05);
  }

  .infoImage {
    width: 200px;
    height: 200px;
  }

  .info-container {
    padding-bottom: 60px
  }
</style>
